﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace zhihu {
    public class TaskFunction{
        private static TaskFunction _taskFunction;
        private bool _run = true;
        private bool _isFirst = true;
        private Thread _thread;
        private object _threadLock = new object();

        public event EventHandler<TaskEventArgs> ShowMsg;

        private TaskFunction() { }

        /// <summary>
        /// 返回TaskFunction的实例
        /// </summary>
        /// <returns></returns>
        public static TaskFunction GetTaskFunction(){
            if (_taskFunction == null) {
                _taskFunction = new TaskFunction();
            }
            return _taskFunction;
        }

        /// <summary>
        /// 用于判断是不是第一次运行,是的话需要绑定事件
        /// </summary>
        /// <returns></returns>
        public bool IsFirst(){
            return _isFirst;
        }

        /// <summary>
        /// 输出消息
        /// </summary>
        /// <param name="logString"></param>
        private void PutLog(string logString) {
            ShowMsg(this, new TaskEventArgs(logString));
        }

        /// <summary>
        /// 开始
        /// </summary>
        public void Start(){
            _isFirst = false;
            _run = true;

            if (_thread != null && _thread.IsAlive) {
                PutLog("线程正在运行");
                return;
            }
            _thread = new Thread(TaskAction);
            
            _thread.Start();
        }

        /// <summary>
        /// 结束
        /// </summary>
        public void Stop(){
            _run = false;

        }
        
        private void TaskAction(){
            try{
                int nPage = 1, nCurQuestionCount = 0;
                PutLog(string.Format(@"本次需采集 {0} 个问题.", GlobalInfo.MaxQuestionCount));
                while (_run) {
                    string listPageUrl =
                        string.Format(@"http://www.zhihu.com/topic/{0}/questions?page={1}", GlobalInfo.TopicID, nPage);
                    int questionCount = ZhihuHelper.GetQuestionByList(GlobalInfo.LoginCookies, listPageUrl, GlobalInfo.AnswerTimes);
                    nCurQuestionCount += questionCount;
                    PutLog(string.Format(@"采集到 {0} 个问题.", nCurQuestionCount));
                    // 跳出条件
                    if (nCurQuestionCount > GlobalInfo.MaxQuestionCount) break;
                    nPage++;
                }

                // 在采集问题的过程中停止,跳过采集答案的过程
                if (_run) {
                    PutLog(string.Format(@"需要采集 {0} 个问题的答案", nCurQuestionCount));

                    // 拿到采集好的问题 key=问题ID value=问题url
                    Dictionary<int, string> dicQuestion = ZhihuHelper.GetQuestionOfDataBase();
                    Queue<QuestionInfo> queueQuestion = new Queue<QuestionInfo>();
                    for (int i = 0; i < dicQuestion.Count; i++) {
                        queueQuestion.Enqueue(new QuestionInfo() {
                            Id = i + 1,
                            Question = dicQuestion.ElementAt(i)
                        });
                    }

                    //int nCount = 1;
                    //foreach (var item in dicQuestion) {
                    //    // 检测跳出
                    //    if (!_run) break;

                    //    PutLog(string.Format(@"采集第 {0}个 {1} 的答案", nCount, item.Key));
                    //    ZhihuHelper.GetAnswerByQuestionPage(GlobalInfo.LoginCookies, item.Value, item.Key);
                    //    nCount++;
                    //}


                    // 多线程采集答案
                    Thread[] threadArray = new Thread[5];
                    for (int i = 0; i < 5; i++) {
                        threadArray[i] = new Thread(() => {
                            while (_run) {
                                // 跳出条件
                                if (queueQuestion.Count == 0) break;
                                QuestionInfo qi;
                                lock (_threadLock) {
                                    qi = queueQuestion.Dequeue();
                                    PutLog(string.Format(@"采集第 {0}/{1}个 问题的答案", qi.Id, nCurQuestionCount, qi.Question.Key));
                                }
                                ZhihuHelper.GetAnswerByQuestionPage(GlobalInfo.LoginCookies, qi.Question.Value, qi.Question.Key);
                            }
                        });
                        threadArray[i].Start();
                    }

                    // 等待线程结束
                    foreach (var item in threadArray) {
                        item.Join();
                    }
                }

                PutLog(@"采集结束.");
            }
            catch (ThreadAbortException){
                PutLog("用户终止.");
            }
        }
    }

    /// <summary>
    /// 事件文本参数
    /// </summary>
    public class TaskEventArgs : EventArgs{
        /// <summary>
        /// 消息的内容
        /// </summary>
        public string MessageString { set; get; }

        public TaskEventArgs(string msg){
            MessageString = msg;
        }
    }
}
